// 微信用户授权接口
var SESSION_ID = sessionStorage.getItem("SESSION_ID");
var USER_ID = sessionStorage.getItem("USER_ID");
function toAuthorization(url) {
    // var authorUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxbbca1747ea1af3ed&redirect_uri='+url+'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';  //测试环境
    var authorUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx2e42a9c1a211e971&redirect_uri='+url+'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';  //正式环境
    window.location.href = authorUrl;
}
//获取url传参
function getPageCode(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = window.location.search.substr(1).match(reg); //匹配目标参数
    if (r != null) return unescape(r[2]); return null; //返回参数值
};
//是否授权链接 ----- 跳转到授权连接
var currentUrl = window.location.href;
if(!SESSION_ID && !getPageCode('code')) {
    toAuthorization(currentUrl);
}

var STORE_ID = sessionStorage.getItem("STORE_ID");
var machCode = sessionStorage.getItem("machCode");// 扫描机器码
var machParams = getPageCode("machCode");
if(machParams) {
    var machArr = machParams.split("$");
    STORE_ID = machArr[0];
    machCode = machArr[1];
    sessionStorage.setItem("STORE_ID",STORE_ID);
    sessionStorage.setItem("machCode",machCode);
}
var IS_BIND = sessionStorage.getItem("IS_BIND"); //0.否，1.是
var companyId = localStorage.getItem("companyId");//个人中心对应的机器ID
// 微信config
wxJsSdkInit(initwxConfig);//初始化jssdk
// 初始化session_id
function initSession_ID(callback) {
    if(!SESSION_ID) {
        var path = 'wx/user/login';
        var params = {
            "CODE":getPageCode('code'),
            "STORE_ID":STORE_ID
        };
        var arg = {};
        arg.async  = false;
        request(path,params,loginCheck,arg);  //登录接口已做同步执行处理
        callback();
    }
}
initSession_ID(function () {});// 初始化session_id old position
function loginCheck(res) {
    var flg = /^0+$/ig.test(res.RSPCD); //全零true
    if(flg) {
        SESSION_ID = res.BODY.SESSION_ID;
        IS_BIND = res.BODY.IS_BIND;
        USER_ID = res.BODY.USER_ID;
        sessionStorage.setItem("IS_BIND",res.BODY.IS_BIND);
        sessionStorage.setItem("SESSION_ID",res.BODY.SESSION_ID);
        sessionStorage.setItem("user_head_img",res.BODY.ICON);
        sessionStorage.setItem("USER_ID",USER_ID);
        return res;
    }
}
//初始化jssdk
function wxJsSdkInit(callback) {
    // JS-SDK初始化参数
    // var newUrl = window.location.href.split("?")[0];
    var jsSdkParams = {
        "URL": window.location.href,
        "STORE_ID":STORE_ID
    }
    // console.log('url',window.location.href);
    // console.log('id',STORE_ID);
    var jsSdkInitPath = "wx/jssdk/config";
    request(jsSdkInitPath,jsSdkParams,callback);
}
// wxJsSdkInit(initwxConfig);//初始化jssdk
//微信配置初始化
function initwxConfig(res) {
    wx.config({
        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
        appId: res.BODY.APPID, // 必填，企业号的唯一标识，此处填写企业号corpid
        timestamp: res.BODY.TIMESTAMP, // 必填，生成签名的时间戳
        nonceStr: res.BODY.NONCE_STR, // 必填，生成签名的随机串
        signature: res.BODY.SIGN,// 必填，签名，见附录1
        jsApiList: [
            'checkJsApi',
            'onMenuShareTimeline',
            'onMenuShareAppMessage',
            'onMenuShareQQ',
            'onMenuShareWeibo',
            'hideMenuItems',
            'showMenuItems',
            'hideAllNonBaseMenuItem',
            'showAllNonBaseMenuItem',
            'translateVoice',
            'startRecord',
            'stopRecord',
            'onRecordEnd',
            'playVoice',
            'pauseVoice',
            'stopVoice',
            'uploadVoice',
            'downloadVoice',
            'chooseImage',
            'previewImage',
            'uploadImage',
            'downloadImage',
            'getNetworkType',
            'openLocation',
            'getLocation',
            'hideOptionMenu',
            'showOptionMenu',
            'closeWindow',
            'scanQRCode',
            'chooseWXPay',
            'openProductSpecificView',
            'addCard',
            'chooseCard',
            'openCard'
        ] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
    });
    wx.error(function(res){
        // alert("配置失败："+res);
        // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
    });
};
function request(path,data,callback,arg) {
    var url = 'http://118.190.15.134:80/kdshop-api/'+path+'?token=htxf';  //正式环境
    var isasync = arg ? (arg.async == false ? arg.async : true) : true;
    $.ajax({
        type: "POST",
        url:url,
        data:JSON.stringify(data),
        contentType: "application/json; charset=utf-8",
        crossDomain: true,
        async: isasync,
        beforeSend: function (xhr) {
            xhr.setRequestHeader("x-sessionid", SESSION_ID); // 请求发起前在头部附加token
        },
        success:function (res) {
            callback(res,arg);
        },
        fail:function (res) {
            callback(res,arg);
        },
    })
};
function znRequest(path,data,callback,arg) {
    var url = 'https://101.37.83.109/NeoSocket/'+path;
    var isasync = arg ? (arg.async == false ? arg.async : true) : true;
    $.ajax({
        type: "POST",
        url:url,
        data:JSON.stringify(data),
        contentType: "application/json; charset=utf-8",
        // dataType:"jsonp",  //数据格式设置为jsonp
        // jsonp:"callback",  //Jquery生成验证参数的名称
        crossDomain: true,
        async: isasync,
        success:function (res) {
            callback(res,arg);
        },
        fail:function (res) {
            callback(res,arg);
        }
    })
};
function getRequest(path, data, callback) {
    data = JSON.stringify(data)
    var url = 'http://122.225.192.35:7080/kdshop-api/'+path+'?token=demo'+data;
    $.get(url,callback);
}
//错误弹框
var boxIsShow = false;
function showErroMsg(text,callback,isError) {  //isError :true,false
var modal = '<div class="showErrorMassage">\n' +
    '    <div class="modal-bg"></div>\n' +
    '    <div class="modal-content">\n' +
    '        <div class="massege-container">\n' +
    '            <img class="massage-head" src=%s alt="">\n' +
    '                <div class="massege-body %s">%s</div>\n' +
    '                <div id="erromsg_confirm" class="massage-footer">确定</div>\n' +
    '        </div>\n' +
    '    </div>\n' +
    '</div>';
    var ico = isError ? "../assets/img/error_icon.png" : "../assets/img/ico_remind.png";
    var alertStyle =  isError ? "" : "no-error-massege-body";
    $("body").append(sprintf(modal,ico,alertStyle,text));
    boxIsShow = true;
if(callback) {
    $("#erromsg_confirm").on("click",callback);
    $("#erromsg_confirm").on("touchstart",function () {
        boxIsShow = false;
    });
}
};
/*$(document).on("click",'.modal-bg,.massage-footer',function (e) {
    $(".showErrorMassage").remove();
});*/
// 微信支付
function onBridgeReady(appId,timestamp,nonceStr,package,signType,paySign,callback){

    //调用微信JS api 支付
        // jsApiCall();
        if (typeof WeixinJSBridge == "undefined")
        {
            if (document.addEventListener)
            {
                document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
            }
            else if (document.attachEvent)
            {
                document.attachEvent('WeixinJSBridgeReady', jsApiCall);
                document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
            }
        }
        else
        {
            WeixinJSBridge.invoke(
                'getBrandWCPayRequest',{
                    "appId" : appId,	 //公众号名称，由商户传入
                    "timeStamp":timestamp,		 //时间戳，自1970年以来的秒数
                    "nonceStr" : nonceStr, //随机串
                    "package" : package,
                    "signType" : signType,		 //微信签名方式:
                    "paySign" : paySign //微信签名
                },
                function (res)
                {
                    if(res.err_msg == "get_brand_wcpay_request:ok")
                    {
                        callback(res);
                    }
                    else
                    {
                        alert("交易失败或已取消！");
                    }
                }
            );
        }
}

//截取中间字符串
function RegBetween(str,a,b) {
    var reg =new RegExp(a + "(\\S*)" + b);
    return str.match(reg)[1]
}
// 拿链接参数
function GetQueryString(name){
    var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if(r!=null)return  unescape(r[2]); return null;
};
function getCompanyId (){
    var company_id = GetQueryString("machCode")&&GetQueryString("machCode").split("$")[1] ? GetQueryString("machCode").split("$")[1] : "未知" ;
    console.log("companyId",company_id);
    if(GetQueryString("machCode")){
        localStorage.setItem("companyId",company_id);
    }
};